from loguru import logger
import pymysql
from setting import Setting


class MySQLClient(object):

    # 进行mysql的连接操作
    def __init__(self):
        self.connect = pymysql.connect(**Setting.db_info)
        print(self.connect)

    # 只做查询操作
    def select(self,sql):
        """
        执行查询语句
        :param sql: SQL语句
        :return:
        """
        with self.connect.cursor() as cursor:
            logger.info("执行的查询语句为:{}".format(sql))
            cursor.execute(sql)
            return cursor.fetchall()

    def execute(self,sql_list):
        """
        执行insert,update,delete操作
        :param sql_list: 需要循环列表中的每一个SQL语句去运行。
        :return:
        """
        with self.connect.cursor() as cursor:
            try:
                for sql in sql_list:
                    logger.info("执行的sql语句为:{}".format(sql))
                    cursor.execute(sql)
            except Exception as e:
                self.connect.rollback()     # 多条sql语句同时不生效 。
            else:
                self.connect.commit()       # 多条SQL语句同时生效

    def close(self):
        self.connect.close()

if __name__ == '__main__':
    mysql = MySQLClient()
